import os,sys
from PIL import Image
from colorama import init as coloramainit 
from colorama import Fore, Back, Style
coloramainit()



def loadDict(filename):
    """loads dict from filename"""
    #print "\r..."#loading dict", filename
    file=open(filename,'r')
    z=file.readlines()
    file.close()
    zz=eval(z[0]) 
    return zz

    

def getShotList(path=None):
    """ get filelist from path jpg png bmp 12 char third '_'"""
    global first
    if path==None:
        path=".\\maps\\"
    slist=dict()
    k=0
    t=''
    try:
        slist=loadDict(path+"data.dict")
    except:
        #print '\033[31;1m'+'Datadict not found'+'\033[0;22m'
        first = True
    if not os.path.isdir(path):
        os.mkdir(path)
        return slist
    for file in os.listdir(path):
        if file[-4:]!="dict" and file[0]!='R' and file[-3:] in ("jpg","png","bmp"):
            if k==0:
                t=file
                k=1
            else:
                try:
                    if slist[t,file] == (None,None):
                        slist[t,file]=(0,0)
                except:
                    slist[t,file]=(0,0)
                t=file
    return slist

def fsc(x,y):
    if x>y:
        return 1
    if x==y:
        return 0
    if y>x:
        return -1

def mstich(imgdict,resultimg,path):
    sdx=sdy=500 #base offset
#    sdy=500 #base offset
    d=125
    n=0
    k=imgdict.keys()
    k.sort(fsc)
    print '\033[33m'+'Multi image sticher'+'\033[0m'+'\n\tBase Offset:',sdx,sdy,"\n\twidth:",d
    for p in k:
        if n==0:
            print "Pic 0 :",str(p[0]),"\tpaste in",(sdx,sdy,sdx+d,sdy+d)
            img1=Image.open(path+str(p[0]))
            resultimg.paste(img1,(sdx,sdy,sdx+d,sdy+d))
        
        img2=Image.open(path+str(p[1]))
        dx=imgdict[p][0]
        dy=imgdict[p][1]
        sdx+=dx
        sdy+=dy
        n+=1

        #print "Pic",n,":",str(p[1]),"\tpaste in",(sdx-d*n,sdy-d*n,sdx-d*n+d,sdy-d*n+d),"dx",dx,"dy",dy
        
        resultimg.paste(img2,(sdx-d*n,sdy-d*n,sdx-d*n+d,sdy-d*n+d))
    return resultimg

